import random
import time

from ascript.android.node import Selector
from ascript.android import action

from .utils import timeSleep, slide, heightPixels, dataTime, widthPixels


# 滚动元素
def elementVisible():
    print('进入滚动获取元素')
    while True:
        element = Selector().path("/FrameLayout/FrameLayout/LynxFlattenUI").find_all()
        if element == None:
            continue
        print('元素个数',len(element))
        for itm in element:
            if itm.text == '去看剧' and itm.path == '/FrameLayout/FrameLayout/LynxFlattenUI' and itm.visible==True and itm.center_y<int(heightPixels/2):
                print('元素成功显示',itm)
                return itm
        slide(num=100)
        timeSleep()

# 吃饭补贴
def kanJuLingqu():
    while True:
        element = Selector().path("/FrameLayout/FrameLayout/LynxFlattenUI").find_all()
        timeSleep()
        if element:
            break
    for itm in element:
        center_x = itm.center_x
        center_y = itm.center_y
        if itm.text == '去看剧' and itm.path == '/FrameLayout/FrameLayout/LynxFlattenUI':
            # 判断元素是否在可见区域
            if itm.visible==False:
                # 不在可见区域则滑动到可见区域
                visible = elementVisible()
                center_x = visible.center_x
                center_y = visible.center_y
            # 获取一个随机日期用于判断退出
            randomTime = random.randint(1 * 60, 10 * 60)
            print('点击去看剧',randomTime ,'s')
            timeSleep()
            action.click(x=center_x, y=center_y, dur=random.randint(20, 500))
            starTime = dataTime()

            while True:
                timeSleep()
                # 判断是否需要上划
                aa = Selector().id("com.phoenix.read:id/abr").text("上滑继续观看短剧").find()
                if aa:
                    print('上滑')
                    action.slide(x=aa.center_x, y=aa.center_y, x1=aa.center_x,
                                 y1=aa.center_y + 100, dur=random.randint(20, 100))
                # 判断日期是否超过，超出则退出
                endTime = dataTime()
                if endTime-starTime>randomTime:
                    # 返回主页
                    action.slide(x=0, y=int(heightPixels / 2), x1=int(widthPixels / 2),
                                 y1=int(heightPixels / 2), dur=20)
                    print('返回主页')
                    time.sleep(2)
                    return
                fuli = Selector().id("com.phoenix.read:id/acv").find()
                if fuli:
                    print('退出返回主页')
                    return
